import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"

//@reduxjs/toolkit提供了一个createAsyncThunk方法专门用来创建异步action
// 参数1是当前action需要的type名称
// 参数2是异步action首次dispatch提交的函数
// 参数2的函数内部执行完异步操作之后,直接把结果return出去即可
const getMovie = createAsyncThunk("movie/getMovie", async () => {
  const result = await axios.get(
    `https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=b9fd987164f6aa47fad266f57dffaa6a`
  )
  // console.log(result)
  return result.data.data.list
})

const movieSlice = createSlice({
  name: "movie",
  initialState: {
    movieList: [],
  },
  reducers: {},
  //如果要给异步action配置reducer处理,需要使用extraReducers配置项
  extraReducers: {
    [getMovie.fulfilled](state, { payload }) {
      // console.log("成功", state, payload)
      state.movieList = payload
    },
    [getMovie.rejected]() {
      console.log("失败")
    },
    [getMovie.pending]() {
      console.log("正在进行中")
    },
  },
})

export default movieSlice.reducer

export { getMovie }
